package org.ecype.diego;

import org.ecype.util.Nulls;

import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;

public class EntityItemProcessor extends EntityProcessor {

	private final Entity entity;

	public EntityItemProcessor(Entity entity) {
		super(entity, URI_ITEM);
		this.entity = entity;
	}

	@Override
	public Cursor query(Uri uri, Uri notifyUri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
		Nulls.checkAreAreNull(selection, selectionArgs, sortOrder);
		return queryHelper(uri, notifyUri, projection, whereIdIs(uri), null, null);
	}

	@Override
	public int delete(Uri uri, Uri notifyUri, String selection, String[] selectionArgs) {
		Nulls.checkAreAreNull(selection, selectionArgs);
		int deleted = deleteHelper(uri, notifyUri, whereIdIs(uri), null);
		if (deleted > 0) {
			for (Reference reference : entity.getReferencesToChild()) {
				if (reference.isCascadeRemove()) {
					provider.delete(Uri.parse(uri + "/" + reference.getLinkToChild()), null, null);
				} else {
					//set null
					ContentValues values = new ContentValues();
					values.put(reference.getLinkToParent(), (String) null);
					provider.update(reference.getChild().getUri(), values, appendParentId(uri, null, reference), null);
				}
			}
			resolver.notifyChange(entity.getUri(), null);
		}
		return deleted;

	}

	@Override
	public int update(Uri uri, Uri notifyUri, ContentValues values, String selection, String[] selectionArgs) {
		Nulls.checkAreAreNull(selection, selectionArgs);
		int result = updateHelper(uri, notifyUri, values, whereIdIs(uri), selectionArgs);
		resolver.notifyChange(entity.getUri(), null);
		return result;
	}
}